package br.com.social.mobile.handler;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import br.com.social.mobile.dao.ChatDAO;
import br.com.social.mobile.dao.ChatGroupDAO;
import br.com.social.mobile.dao.ChatMessageDAO;
import br.com.social.mobile.dto.ChatMessageDto;
import br.com.social.mobile.entities.Chat;
import br.com.social.mobile.entities.ChatGroup;
import br.com.social.mobile.entities.ChatMessage;
import br.com.social.mobile.entities.User;


public class ChatHandler {
	
	private Logger logger = Logger.getLogger(ChatHandler.class);
	
	
	public Chat createChat(long idUserTo, long idUserFrom) {
		
		Chat chat = null;
		
		try {

			ChatDAO chatDAO = new ChatDAO();
			ChatGroupDAO chatGroupDAO = new ChatGroupDAO();
			
			chat = new Chat();
			chat.setDtCreate(new Date());
			
			if(idUserTo > idUserFrom){
				chat.setNuIdUsers(idUserFrom + "|" + idUserTo);
			}else{
				chat.setNuIdUsers(idUserTo + "|" + idUserFrom);
			}
			
			chatDAO.save(chat);
			

			ChatGroup chatGroup = new ChatGroup();
			
			chatGroup.setNuIdChat(chat.getId());
			chatGroup.setNuIdUser(idUserTo);
			chatGroup.setIsActive(Boolean.TRUE);
			chatGroup.setDtLastUpdate(new Date());
			chatGroupDAO.save(chatGroup);
			
			chatGroup = new ChatGroup();
			
			chatGroup.setNuIdChat(chat.getId());
			chatGroup.setNuIdUser(idUserFrom);
			chatGroup.setIsActive(Boolean.TRUE);
			chatGroup.setDtLastUpdate(new Date());
			chatGroupDAO.save(chatGroup);			
			
			
		} catch (Exception e) {
			logger.error(e);
			
		}
		
		return chat;
	}
	
	
	public void sendMessage(long idChat, long idUserTo, String message){		
		
		ChatMessage chatMessage = null;
		
		try{
			
			chatMessage = new ChatMessage();
			chatMessage.setNuIdChat(idChat);
			chatMessage.setDsMessage(message);
			chatMessage.setDtMessage(new Date());
			chatMessage.setIdUserSend(idUserTo);
			
			ChatMessageDAO chatMessageDAO = new ChatMessageDAO();
			chatMessageDAO.save(chatMessage);
			
		} catch (Exception e){
			logger.error(e);
		}		
	}
	
	
	public List<ChatMessageDto> getListChatMessage(long nuIdUser) {
		
		ChatMessageDto chatMessageDto = null;
		ChatMessageDAO chatMessageDAO = null;
		List<ChatMessageDto> listMessage = null;
		
		try{
			chatMessageDAO = new ChatMessageDAO();
			listMessage = chatMessageDAO.getListChatMessage(nuIdUser);
			
		}catch(Exception e){
			logger.error(e);
		}
		
		return listMessage;
	}
	
	
	public void updateStatusChat(long nuIdChat, long nuIdUser, Boolean flgActive){
		
		ChatGroupDAO chatGroupDAO = null;
		
		try{
			chatGroupDAO = new ChatGroupDAO();
			chatGroupDAO.updateStatusChat(nuIdChat, nuIdUser, flgActive);

		}catch(Exception e){
			logger.error(e);
		}
	}
	
}
